package com.xn.app.muying.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.Constants;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.ImageUtils;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.util.UploadUtil;
import com.zhuge.analysis.stat.ZhugeSDK;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.Request;

/**
 * 化验单解读
 * Created by Administrator on 2016/12/26.
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public class SheetActivity extends BaseActivity implements View.OnClickListener {
    //标题文字
    private TextView title_name = null;
    //返回键
    private ImageView img_back = null;
    //拍化验单
    private View camera = null;
    private ImageView activity_sheet_camera_img = null;
    //数据库
    private DBManager db = null;
    //加载框
    MyAlertDialog dialog = null;
    //是否可以使用化验单解读
    private String bodys = null;
    File f;
    Bitmap photo;
    //加载框
    AlertDialog dialog1;
    //相机选择
    MyAlertDialog photo_dialog;
    //图片保存路径
    private File downloadUrl = new File(Environment.getExternalStorageDirectory() + "/temp");
    //图片名称
    private String imageFileName = DateUtils.getNumberDate() + ".jpg";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sheet);
        db = new DBManager(this);
        if (NetworkUtil.isNetworkAvailable(this)) {
            initView();
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }
    }

    private void initView() {
        try {
            ZhugeSDK.getInstance().track(getApplicationContext(), "化验单解读");
        } catch (Exception e) {
            e.printStackTrace();
        }
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        camera = findViewById(R.id.activity_sheet_camera);
        activity_sheet_camera_img = (ImageView) findViewById(R.id.activity_sheet_camera_img);
        Button history = (Button) findViewById(R.id.activity_sheet_history);
        title_name.setText("化验单解读");
        img_back.setOnClickListener(this);
        camera.setOnClickListener(this);
        activity_sheet_camera_img.setOnClickListener(this);
        history.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        //1代表true,0代表flase
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;

            case R.id.activity_sheet_camera:
                //判断是否可使用
                if (NetworkUtil.isNetworkAvailable(this)) {
//                    dialog1 = new MyAlertDialog().ShowDialog(SheetActivity.this, R.layout.dialog_loading);
//                    dialog1.setCancelable(true);
//                    ifSheet();
                    verifyStoragePermissions(SheetActivity.this);
                } else {
                    ToastUtil.showToast(this, R.string.no_network_hint);
                }
                break;
            case R.id.activity_sheet_camera_img:
                //判断是否可使用
                if (NetworkUtil.isNetworkAvailable(this)) {
//                    dialog1 = new MyAlertDialog().ShowDialog(SheetActivity.this, R.layout.dialog_loading);
//                    dialog1.setCancelable(true);
//                    ifSheet();
                    verifyStoragePermissions(SheetActivity.this);
                } else {
                    ToastUtil.showToast(this, R.string.no_network_hint);
                }
                break;
            case R.id.activity_sheet_history:
                Intent intent = new Intent();
                intent.setClass(SheetActivity.this, ReadHistoryActivity.class);
                intent.putExtra("data", "1");
                startActivity(intent);
                break;
        }
    }

    /**
     * 相册返回的数据
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        try {
            switch (requestCode) {
                //相册
                case 1:
                    f = ImageUtils.getPhotoFromResult(this, data);
                    break;
                //相机
                case 2:
                    f = new File(downloadUrl, Constants.getStringByName(SheetActivity.this, "photo"));
                    break;
            }
            //跳转页面
            if (f != null && !f.getAbsolutePath().equals("") && !f.getAbsolutePath().equals("null")) {
                if (NetworkUtil.isNetworkAvailable(SheetActivity.this)) {
                    setImgData(requestCode);
                    Intent cameraintent = new Intent(SheetActivity.this, ReadHistoryActivity.class);
                    cameraintent.putExtra("data", DateUtils.gettimeDate1());
                    startActivity(cameraintent);
                } else {
                    ToastUtil.showToast(SheetActivity.this, R.string.no_network_hint);
                }
            } else {
                ToastUtil.showToast(SheetActivity.this, "图片选择失败,请从图库选择上传");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 显示是否开通会员对话框
     */
    private void showVipDialog() {
        try {
            //加载弹出框
            dialog = new MyAlertDialog();
            dialog.vip_Dialog(SheetActivity.this, R.layout.vip_dialog);
            //设置内容
            TextView data = dialog.getData();
            data.setText("开通蓓儿母婴会员，立享每日8次解读机会，更有健康档案在线查看、远程胎心监护、预约挂号等超多特权呦！");
            //设置取消按钮
            TextView getCancel_text = dialog.getCancel_text();
            getCancel_text.setText("取消");
            getCancel_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismissOut();
                }
            });
            //设置确认按钮
            TextView getConfirm_text = dialog.getConfirm_text();
            getConfirm_text.setText("开通会员");
            getConfirm_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismissOut();
                    Intent intent = new Intent();
                    intent.setClass(SheetActivity.this, VIPActivity.class);
                    startActivity(intent);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void ifSheet() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.IfSheet).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    bodys = response.body().string();
                    int code = response.code();
                    if (code == 200 || code == 204) {
                        loginHandler.sendEmptyMessage(1);
                    } else {
                        loginHandler.sendEmptyMessage(2);
                    }
                } catch (IOException e) {
                    loginHandler.sendEmptyMessage(2);
                }
            }
        }).start();
    }

    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    /**
     * Checks if the app has permission to write to device storage
     * <p>
     * If the app does not has permission then the user will be prompted to
     * grant permissions
     *
     * @param activity
     */
    public void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        } else {

            //加载弹出框
            photo_dialog = new MyAlertDialog();
            photo_dialog.PhotoGraph_Dialog(SheetActivity.this, R.layout.photo_graph_dialog);
            //设置取消
            TextView data = photo_dialog.getData();
            data.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    photo_dialog.dismissPhoto();
                }
            });
            //设置拍照
            ImageView image1 = photo_dialog.getImage1();
            image1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    photo_dialog.dismissPhoto();
                    if (downloadUrl.exists()) {
                        downloadUrl.mkdir();
                    }
                    f = new File(downloadUrl, imageFileName);
                    Constants.setStringByName(SheetActivity.this, "photo", imageFileName);
                    Uri photoURI = null;
                    //如果版本大于等于androidN
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        photoURI = FileProvider.getUriForFile(SheetActivity.this, "com.xn.app.muying.fileProvider", f);
                    } else {
                        photoURI = Uri.fromFile(f);
                    }
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                    startActivityForResult(intent, 2);
                }
            });
            //设置相册
            ImageView image2 = photo_dialog.getImage2();
            image2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    photo_dialog.dismissPhoto();
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "选择图片"), 1);
                }
            });
        }
    }

    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            if (dialog1 != null) {
                dialog1.dismiss();
            }
            switch (msg.what) {
                case 1:
                    if (bodys != null && bodys.equals("true")) {
                        verifyStoragePermissions(SheetActivity.this);
                    } else {
                        if (db.select("isVIP").equals("1")) {
                            ToastUtil.showToast(SheetActivity.this, "今日次数已经用完！");
                        } else {
                            showVipDialog();
                        }
                    }
                    break;
                case 2:
                    ToastUtil.showToast(SheetActivity.this, "今日次数已经用完！");
                    break;
                case 3:
                    //如果不在前台，停止线程刷新时间
                    ActivityManager am = (ActivityManager) SheetActivity.this.getSystemService(ACTIVITY_SERVICE);
                    ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
                    //如果当期要刷新的页面在前台
                    if ("com.xn.app.muying.activity.ReadHistoryActivity".equals(cn.getClassName())) {
                        Intent i = new Intent(SheetActivity.this, ReadHistoryActivity.class);
                        i.putExtra("data", "1");
                        SheetActivity.this.startActivity(i);
                    }
                    break;
                case 4:
                    ToastUtil.showToast(SheetActivity.this, "图片上传失败,请返回重新上传图片");
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 图片上传
     *
     * @param requestCode
     */
    private void setImgData(final int requestCode) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (requestCode == 1) {
                        Bitmap bmp = null;
                        if (f != null) {
                            bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
                            bmp = ImageCompressL(bmp);
                            //保存图片
                            if (!downloadUrl.exists()) {
                                downloadUrl.mkdir();
                            }
                            f = new File(downloadUrl, imageFileName);
                            FileOutputStream out = null;
                            try {
                                out = new FileOutputStream(f);
                                if (bmp.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                                    out.flush();
                                    out.close();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    //上传图片
                    String str = UploadUtil.uploadFile(f, APIMethod.CaneraActivity, db.select("access_token"));
                    if (str.equals("200")) {
                        loginHandler.sendEmptyMessage(3);
                    } else {
                        loginHandler.sendEmptyMessage(4);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    loginHandler.sendEmptyMessage(4);
                }
            }
        }).start();
    }

    /**
     * 图片压缩
     *
     * @param bitmap
     * @return
     */
    private Bitmap ImageCompressL(Bitmap bitmap) {
        // 获取Android屏幕的服务
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        //图片允许最大空间   屏幕宽度像素
        double maxSize = wm.getDefaultDisplay().getWidth();
        //将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        //将字节换成KB
        double mid = b.length / 1024;
        //判断bitmap占用空间是否大于允许最大空间  如果大于则压缩 小于则不压缩
        if (mid > maxSize) {
            //获取bitmap大小 是允许最大大小的多少倍
            double i = mid / maxSize;
            //开始压缩  此处用到平方根 将宽带和高度压缩掉对应的平方根倍 （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
            bitmap = zoomImage(bitmap, bitmap.getWidth() / Math.sqrt(i),
                    bitmap.getHeight() / Math.sqrt(i));
        }
        return bitmap;
    }

    /***
     * 图片的缩放方法
     *
     * @param bgimage   ：源图片资源
     * @param newWidth  ：缩放后宽度
     * @param newHeight ：缩放后高度
     * @return
     */
    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
